package com.linko.intelligent.common.interceptor;

import com.google.gson.Gson;
import com.linko.intelligent.base.UserInfo;
import com.linko.intelligent.common.util.UserContext;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author yuan
 * @create 2021/6/18 3:08 下午
 */
@Slf4j
@Configuration
public class FeignConfiguration implements RequestInterceptor {

    Gson gson = new Gson();

    @Override
    public void apply(RequestTemplate requestTemplate) {
        System.out.println("FeignConfiguration:URL:" + requestTemplate.url());
        Map<String, String> headers = getHeaders(getHttpServletRequest());
        for (String headerName : headers.keySet()) {
            requestTemplate.header(headerName, headers.get(headerName));
        }
        if (UserContext.getUserSession() != null) {
            UserInfo info = UserContext.getUserSession();
            requestTemplate.header("AuthorizationUserInfo", gson.toJson(info));
        }

    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            log.debug("获取不到请求");
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        if (request == null) {
            log.debug("获取不到请求头中参数");
            return map;
        }
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }

}